<template>
  <div>
    <el-table
      :data="allServiceList"
      style="width: 100%"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center' }"
    >
      <el-table-column label="服务名称">
        <template slot-scope="scope">
          <el-tooltip
            effect="dark"
            :content="scope.row.appZhname"
            placement="bottom-start"
            popper-class="tooltipClass"
            :disabled="isShowTooltip"
          >
            <div class="descSpan" @mouseover="onMouseOver($event)">
              {{ scope.row.appZhname }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="部署名称">
        <template slot-scope="scope">
          <el-tooltip
            effect="dark"
            :content="scope.row.deployName"
            placement="bottom-start"
            popper-class="tooltipClass"
            :disabled="isShowTooltip"
          >
            <div class="descSpan" @mouseover="onMouseOver($event)">
              {{ scope.row.deployName }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="服务描述">
        <template slot-scope="scope">
          <el-tooltip
            effect="dark"
            :content="scope.row.appDescription"
            placement="bottom-start"
            popper-class="tooltipClass"
          >
            <div class="descSpan">
              {{ scope.row.appDescription }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="appVersion" label="服务版本"/>
      <el-table-column label="来源">
        <template slot-scope="scope">
          <span>
            {{ getInstanceType(scope.row.arranged, scope.row.deployType) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="host" label="地址"/>
      <el-table-column prop="updateTime" label="创建时间" width="180px"/>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag v-if="showStatusTag(scope.row) === 2" type="success">
            运行中
          </el-tag>
          <el-tag
            v-else-if="
              showStatusTag(scope.row) === 3 ||
              showStatusTag(scope.row) === 5 ||
              showStatusTag(scope.row) === 0
            "
            type="info"
          >
            {{ scope.row.deployStatus }}
          </el-tag>
          <el-tag v-else-if="showStatusTag(scope.row) === 4" type="warning"
          >异常
          </el-tag>
          <el-tag v-else-if="showStatusTag(scope.row) === 1">更新中</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" style="padding: 0"
                     v-show="getInstanceType(scope.row.arranged, scope.row.deployType) === '引用'"
                     @click="showDetails(scope.row)"
          >
            详情
          </el-button>
          <el-dropdown
            trigger="click"
            @command="
              (command) => {
                handleCommand(command, scope.row);
              }
            "
            :disabled="getInstanceType(scope.row.arranged, scope.row.deployType) === '外部服务'"
            v-show="getInstanceType(scope.row.arranged, scope.row.deployType) !== '引用'"
          >
            <el-button type="text" style="padding: 0"
                       :disabled="getInstanceType(scope.row.arranged, scope.row.deployType) === '外部服务'">
              更多<i class="el-icon-arrow-down el-icon--right"/>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <!--                @click="startSingleService(scope.row)"-->
              <!--              @click="stopSingleService(scope.row)"-->
              <el-dropdown-item
                command="start"
                :disabled="
                  showStatusTag(scope.row) === 2 ||
                  showStatusTag(scope.row) === 4 ||
                  showStatusTag(scope.row) === 1
                "
              >启动
              </el-dropdown-item>
              <el-dropdown-item
                command="stop"
                :disabled="
                  showStatusTag(scope.row) === 3 ||
                  showStatusTag(scope.row) === 5 ||
                  showStatusTag(scope.row) === 0
                "
              >停止
              </el-dropdown-item>
              <el-dropdown-item
                command="detail"
                :disabled="
                  showStatusTag(scope.row) === 3 ||
                  showStatusTag(scope.row) === 5 ||
                  showStatusTag(scope.row) === 0
                "
              >详情
              </el-dropdown-item>
              <el-dropdown-item command="yaml"
                                v-show="!getInstanceType(scope.row.arranged, scope.row.deployType).includes('云原生')"
              >查看yaml
              </el-dropdown-item>
              <el-dropdown-item command="configuration"
                                v-show="!getInstanceType(scope.row.arranged, scope.row.deployType).includes('云原生')"
              >配置
              </el-dropdown-item>
              <el-dropdown-item command="update">升级</el-dropdown-item>
              <el-dropdown-item command="rollback">回滚</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <div v-if="dialogVisible">
      <el-dialog
        :title="'服务:' + serviceInstance.appName + ' 详情'"
        :visible.sync="dialogVisible"
        width="70%"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        append-to-body
      >
        <service-instance-detail-dialog :service-instance="serviceInstance"></service-instance-detail-dialog>
      </el-dialog>
    </div>
    <div v-if="serviceSetUp">
      <el-dialog
        :title="'服务' + titleForDialog"
        :visible.sync="serviceSetUp"
        width="70%"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        append-to-body
      >
        <service-instance-configuration
          ref="serviceInstanceSetUp"
          :open-type="openType"
          :deploy-id="deployId"
        />
      </el-dialog>
    </div>
    <div v-if="yamlDialog">
      <el-dialog
        title="查看yaml"
        :visible.sync="yamlDialog"
        width="50%"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        append-to-body
      >
        <div style="height: 60vh; overflow-y: auto">
          <codemirror v-model="yamlString" :options="cmOptions"/>
        </div>
      </el-dialog>
    </div>
    <div v-if="rollbackDialog">
      <el-dialog
        title="服务回滚"
        :visible.sync="rollbackDialog"
        width="450px"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        center
        append-to-body
      >
        <service-instance-rollback-dialog
          ref="rollbackDialogOperate"
          :service-instance="serviceInstance"
        />
      </el-dialog>
    </div>
    <div v-if="updateYamlCloudInfoDialog">
      <update-yaml-cloud-info
        ref="updateYamlCloudInfoRef"
        :tmpCloudNative="tmpCloudNative"
      ></update-yaml-cloud-info>
    </div>
    <div v-if="rollbackYamlCloudInfoDialog">
      <rollback-yaml-cloud-info
        ref="rollbackYamlCloudInfoRef"
        :selectYamlId="selectYamlId"
        :selectYamlName="selectYamlName"
      ></rollback-yaml-cloud-info>
    </div>
    <div v-if="detailYamlInfoDialog">
      <detail-yaml-info
        ref="detailYamlInfoRef"
        :tmpCloudNative="tmpCloudNativeInfo"
        append-to-body
      ></detail-yaml-info>
    </div>
  </div>
</template>

<script>
  import ServiceInstanceDetailDialog from "@/views/ApplicationManage/ServiceInstanceDetailDialog.vue";
  import ServiceInstanceConfiguration from "@/views/ApplicationManage/ServiceInstanceConfiguration.vue";
  import ServiceInstanceRollbackDialog from "@/views/ApplicationManage/ServiceInstanceRollbackDialog.vue";
  import {codemirror} from "vue-codemirror";
  import "codemirror/lib/codemirror.css";
  import "codemirror/mode/yaml/yaml.js";
  import DetailYamlInfo from "@/views/ApplicationManage/CloudNative/DetailYamlInfo.vue";
  import UpdateYamlCloudInfo from "@/views/ApplicationManage/ServiceGroupManage/UpdateYamlCloudInfo.vue";
  import RollbackYamlCloudInfo from "@/views/ApplicationManage/ServiceGroupManage/RollbackYamlCloudInfo.vue";

  export default {
    name: "ServiceGroupDetailServiceListDialog",
    components: {
      RollbackYamlCloudInfo,
      UpdateYamlCloudInfo,
      ServiceInstanceRollbackDialog,
      ServiceInstanceConfiguration,
      ServiceInstanceDetailDialog,
      DetailYamlInfo,
      codemirror,
    },
    props: ["allServiceList"],
    data() {
      return {
        serviceInstance: {},
        dialogVisible: false,
        serviceSetUp: false,
        titleForDialog: "",
        openType: "",
        deployId: "",
        rollbackDialog: false,
        yamlDialog: false,
        yamlString: "",
        yamlName: "",
        cmOptions: {
          mode: "yaml", // 使用YAML模式
          theme: "default", // 使用默认主题
          lineNumbers: true, // 显示行号
          line: true, // 显示行高亮
          styleActiveLine: true, // 高亮当前行
          matchBrackets: true, // 括号匹配高亮
          autoCloseBrackets: true, // 自动闭合括号
          gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], // 显示行号和折叠标记
          foldGutter: true, // 启用折叠功能
          extraKeys: {"Ctrl-Space": "autocomplete"}, // 添加自动完成快捷键
          readOnly: true, // 禁止编辑
        },
        tmpCloudNative: {},
        updateYamlCloudInfoDialog: false,
        rollbackYamlCloudInfoDialog: false,
        selectYamlId: "",
        selectYamlName: "",
        tmpCloudNativeInfo: "",
        detailYamlInfoDialog: false,
        isShowTooltip: false,
      };
    },
    methods: {
      onMouseOver(event) {
        const ev = event.target;
        const evWeight = ev.scrollWidth;
        const contentWidth = ev.clientWidth;
        if (evWeight > contentWidth) {
          this.isShowTooltip = false;
        } else {
          this.isShowTooltip = true;
        }
      },
      showStatusTag(row) {
        let tmpStatus = 0;
        switch (row.deployStatus) {
          case "未部署":
            tmpStatus = 0;
            break;
          case "更新中":
            tmpStatus = 1;
            break;
          case "运行中":
            tmpStatus = 2;
            break;
          case "已停止":
            tmpStatus = 3;
            break;
          case "异常":
            tmpStatus = 4;
            break;
          default:
            tmpStatus = 5;
        }
        return tmpStatus;
      },
      stopSingleService(row) {
        if (row.deployStatus === "未部署" || row.deployStatus === "已停止") {
          this.$message.error(
            "服务：" +
            row.deployName +
            "状态为：" +
            row.deployStatus +
            "，请先取消勾选。"
          );
          return;
        }
        this.$appManageApi
          .stopYamlDeploy([row.id])
          .then((res) => {
            if (res && res.code === 200) {
              this.$message.success(res.msg);
              // this.getListYamlDeploy();
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      startSingleService(row) {
        if (
          row.deployStatus === "更新中" ||
          row.deployStatus === "运行中" ||
          row.deployStatus === "异常"
        ) {
          this.$message.error(
            "服务：" +
            row.deployName +
            "状态为：" +
            row.deployStatus +
            "，请取消勾选。"
          );
          return;
        }
        this.$appManageApi
          .startYamlDeploy([row.id])
          .then((res) => {
            if (res && res.code === 200) {
              this.$message.success(res.msg);
              // this.getListYamlDeploy();
            }
          })
          .catch((error) => {
            this.$message.error(error.message);
          });
      },
      handleCommand(command, serviceInstance) {
        if (command === "configuration") {
          if (
            serviceInstance.deployStatus === "更新中" ||
            serviceInstance.deployStatus === "运行中" ||
            serviceInstance.deployStatus === "异常"
          ) {
            this.$message.warning(
              "服务：" +
              serviceInstance.deployName +
              "状态为：" +
              serviceInstance.deployStatus +
              "，请先停止服务。"
            );
            return;
          }
          this.openType = "configuration";
          this.titleForDialog = "配置";
          this.serviceSetUp = true;
          this.deployId = serviceInstance.id;
          this.$nextTick(() => {
            if (this.$refs.serviceInstanceSetUp !== undefined) {
              this.$refs.serviceInstanceSetUp.$on(
                "closeServiceSetUpDialog",
                this.closeServiceSetUpDialog
              );
            }
          });
        } else if (command === "update") {
          if (this.getInstanceType(serviceInstance.arranged, serviceInstance.deployType) === '服务包') {
            this.openType = "update";
            this.titleForDialog = "升级";
            this.serviceSetUp = true;
            this.deployId = serviceInstance.id;
            this.$nextTick(() => {
              if (this.$refs.serviceInstanceSetUp !== undefined) {
                this.$refs.serviceInstanceSetUp.$on(
                  "closeServiceSetUpDialog",
                  this.closeServiceSetUpDialog
                );
              }
            });
          } else if (this.getInstanceType(serviceInstance.arranged, serviceInstance.deployType) === '云原生') {
            this.$appManageApi.getCloudYamlById(serviceInstance.id).then((res) => {
              if (res && res.code === 200) {
                this.updateYamlCloudInfoDialog = true;
                this.tmpCloudNative = res.data;
                this.$nextTick(() => {
                  if (this.$refs.updateYamlCloudInfoRef !== undefined) {
                    this.$refs.updateYamlCloudInfoRef.dialogVisible = true;
                    this.$refs.updateYamlCloudInfoRef.$on(
                      "closeUpdateYamlCloudInfoRef",
                      this.closeUpdateYamlCloudInfoRef
                    );
                  }
                });
              }
            });
          }
        } else if (command === "rollback") {
          if (this.getInstanceType(serviceInstance.arranged, serviceInstance.deployType) === '服务包') {
            this.rollbackDialog = true;
            this.serviceInstance = serviceInstance;
            this.$nextTick(() => {
              if (this.$refs.rollbackDialogOperate !== undefined) {
                this.$refs.rollbackDialogOperate.$on(
                  "closeRollbackDialog",
                  this.closeRollbackDialog
                );
              }
            });
          } else if (this.getInstanceType(serviceInstance.arranged, serviceInstance.deployType) === '云原生') {
            this.selectYamlId = serviceInstance.id;
            this.selectYamlName = serviceInstance.appZhname;
            this.rollbackYamlCloudInfoDialog = true;
            this.$nextTick(() => {
              if (this.$refs.rollbackYamlCloudInfoRef !== undefined) {
                this.$refs.rollbackYamlCloudInfoRef.rollbackYamlInfoDialog = true;
                this.$refs.rollbackYamlCloudInfoRef.$on(
                  "closeRollbackYamlCloudInfoRef",
                  this.closeRollbackYamlCloudInfoRef
                );
              }
            });
          }
        } else if (command === "detail") {
          this.serviceInstanceDetail(serviceInstance);
        } else if (command === "start") {
          if (this.getInstanceType(serviceInstance.arranged, serviceInstance.deployType) === '服务包') {
            this.startSingleService(serviceInstance);
          } else if (this.getInstanceType(serviceInstance.arranged, serviceInstance.deployType) === '云原生') {
            this.$appManageApi.startCloudYaml([serviceInstance.id]).then((res) => {
              if (res && res.code === 200) {
                this.$message.success(res.data);
              }
            });
          }
        } else if (command === "stop") {
          if (this.getInstanceType(serviceInstance.arranged, serviceInstance.deployType) === '服务包') {
            this.stopSingleService(serviceInstance);
          } else if (this.getInstanceType(serviceInstance.arranged, serviceInstance.deployType) === '云原生') {
            this.$appManageApi.stopCloudYaml([serviceInstance.id]).then((res) => {
              if (res && res.code === 200) {
                this.$message.success(res.data);
              }
            });
          }
        } else if (command === "yaml") {
          this.getYamlDetail(serviceInstance);
        }
      },
      showDetails(row) {
        if (row.arranged === 1 && row.deployType === 0) {
          this.serviceInstanceDetail(row);
        } else if (row.arranged === 1 && row.deployType === 1) {
          this.detailYamlInfoDialog = true;
          this.tmpCloudNativeInfo = row;
          this.$nextTick(() => {
            if (this.$refs.detailYamlInfoRef !== undefined) {
              this.$refs.detailYamlInfoRef.dialogVisible = true;
              this.$refs.detailYamlInfoRef.$on(
                "closeDetailCloudNative",
                this.closeDetailCloudNative
              );
            }
          });
        }
      },
      closeDetailCloudNative() {
        this.detailYamlInfoDialog = false;
        this.$refs.detailYamlInfoRef.$off("closeDetailCloudNative");
      },
      closeUpdateYamlCloudInfoRef() {
        this.updateYamlCloudInfoDialog = false;
        this.$refs.updateYamlCloudInfoRef.$off("closeUpdateYamlCloudInfoRef");
      },
      closeRollbackYamlCloudInfoRef() {
        this.rollbackYamlCloudInfoDialog = false;
        this.$refs.rollbackYamlCloudInfoRef.$off("closeRollbackYamlCloudInfoRef");
      },
      getYamlDetail(serviceInstance) {
        this.deployId = serviceInstance.id;
        this.$appManageApi.getYamlDetail(this.deployId).then((res) => {
          this.yamlString = res.data;
        });
        this.yamlDialog = true;
      },
      closeServiceSetUpDialog() {
        this.serviceSetUp = false;
      },
      serviceInstanceDetail(row) {
        this.dialogVisible = true;
        this.serviceInstance = row;
        // this.detailYamlInfoDialog = true;
        // this.tmpCloudNativeInfo = row;
        // this.$nextTick(() => {
        //   if (this.$refs.detailYamlInfoRef !== undefined) {
        //     this.$refs.detailYamlInfoRef.dialogVisible = true;
        //     this.$refs.detailYamlInfoRef.$on(
        //       "closeDetailCloudNative",
        //       this.closeDetailCloudNative
        //     );
        //   }
        // });
      },
      getInstanceType(arranged, deployType) {
        const arrangedMap = {
          "0-0": '服务包',
          "0-1": '云原生',
          "1-0": '引用',
          "1-1": '引用',
          "2-0": '外部服务',
          "2-1": '外部服务',
        }
        return arrangedMap[`${arranged}-${deployType}`] || '未知类型'
      }
    },
  };
</script>

<style>
  .tooltipClass {
    width: 300px;
  }
</style>
